//
//  PPAlbumContentTagsTableViewTagsFieldCell.m
//  pickpic
//
//  Created by Jinxiao on 9/16/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPAlbumContentTagsTableHeaderView.h"

#import "TITokenField.h"

@interface PPAlbumContentTagsTableHeaderView () <TITokenFieldDelegate, UITextViewDelegate>
@property (readwrite, nonatomic, strong) TITokenFieldView *tagsField;
@property (readwrite, nonatomic, strong) CALayer *topLayer;
@property (readwrite, nonatomic, strong) CALayer *bottomLayer;
@end

@implementation PPAlbumContentTagsTableHeaderView

- (instancetype)init {
    self = [super init];

    _tagsField = [[TITokenFieldView alloc] initWithFrame:CGRectZero];
    [self addSubview:_tagsField];

    _tagsField.tokenField.promptText = nil;
    _tagsField.tokenField.returnKeyType = UIReturnKeyDone;
    _tagsField.tokenField.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"输入标签" attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:16], NSForegroundColorAttributeName : [UIColor colorWithRGBHex:0xb2b2b2]}];
    [_tagsField.tokenField setDelegate:self];
    [_tagsField setShouldSearchInBackground:NO];
    [_tagsField setShouldSortResults:NO];
    [_tagsField.tokenField addTarget:self action:@selector(tokenFieldFrameDidChange:) forControlEvents:(UIControlEvents)TITokenFieldControlEventFrameDidChange];
    [_tagsField.tokenField setTokenizingCharacters:[NSCharacterSet characterSetWithCharactersInString:@",;."]];

    _topLayer = [self addTopBorderWithColor:kLineColor andWidth:kLineWidth];
    _bottomLayer = [self addBottomBorderWithColor:kLineColor andWidth:kLineWidth];

    return self;
}

- (void)didMoveToWindow {
    [super didMoveToWindow];

    [_tagsField becomeFirstResponder];
}

- (void)layoutSubviews {
    [super layoutSubviews];

    _tagsField.frame = CGRectMake(0, 0, self.width, self.height);

    _topLayer.frame = CGRectMake(0, 0, self.width, kLineWidth);
    _bottomLayer.frame = CGRectMake(0, self.height - kLineWidth, self.width, kLineWidth);
}

- (void)addTag:(PPAlbumTagElement *)tag {
    TIToken *token = [[TIToken alloc] initWithTitle:tag.name representedObject:tag];
    [_tagsField.tokenField addToken:token];
}

- (void)removeTag:(PPAlbumTagElement *)tag {
    [_tagsField.tokenField.tokens enumerateObjectsUsingBlock:^(TIToken *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
        if([obj.title isEqualToString:tag.name]) {
            [_tagsField.tokenField removeToken:obj];
        }
    }];
}

#pragma mark - TITokenDelegate

- (void)tokenFieldFrameDidChange:(TITokenField *)tokenField {
    _tagsField.height = tokenField.height;

    self.height = _tagsField.height;

    [_delegate headerViewDidUpdateFrame:self];
}

- (void)textViewDidChange:(UITextView *)textView {

    CGFloat oldHeight = _tagsField.frame.size.height - _tagsField.tokenField.frame.size.height;
    CGFloat newHeight = textView.contentSize.height + textView.font.lineHeight;

    CGRect newTextFrame = textView.frame;
    newTextFrame.size = textView.contentSize;
    newTextFrame.size.height = newHeight;

    CGRect newFrame = _tagsField.contentView.frame;
    newFrame.size.height = newHeight;

    if(newHeight < oldHeight) {
        newTextFrame.size.height = oldHeight;
        newFrame.size.height = oldHeight;
    }

    [_tagsField.contentView setFrame:newFrame];
    [textView setFrame:newTextFrame];
    [_tagsField updateContentSize];
}


#pragma mark - Custom Search

- (BOOL)tokenField:(TITokenField *)field shouldUseCustomSearchForSearchString:(NSString *)searchString {
    return ([searchString isEqualToString:@"contributors"]);
}

- (void)tokenField:(TITokenField *)field performCustomSearchForSearchString:(NSString *)searchString withCompletionHandler:(void (^)(NSArray *))completionHandler {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //Send a Github API request to retrieve the Contributors of this project.
        //Using a syncrhonous request in a Background Thread to not over-complexify the demo project
        NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://api.github.com/repos/thermogl/TITokenField/contributors"]];
        NSURLResponse *response = nil;
        NSError *error = nil;
        NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];

        NSMutableArray *results = [[NSMutableArray alloc] init];

        if(error == nil) {
            NSError *errorJSON;
            NSArray *contributors = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errorJSON];

            for(NSDictionary *user in contributors) {
                [results addObject:[user objectForKey:@"login"]];
            }
        }

        dispatch_async(dispatch_get_main_queue(), ^(void) {
            //Finally call the completionHandler with the results array!
            completionHandler(results);
        });
    });
}

- (void)tokenField:(TITokenField *)tokenField didAddToken:(TIToken *)token {

    PPAlbumTagElement *tag = token.representedObject;

    if(tag == nil) {
        tag = [[PPAlbumTagElement alloc] init];
        tag.name = token.title;
        token.representedObject = tag;
    }

    [_delegate headerView:self didAddTag:token.representedObject];

}

- (void)tokenField:(TITokenField *)tokenField didRemoveToken:(TIToken *)token {

    [_delegate headerView:self didRemoveTag:token.representedObject];

}

@end
